import { parse } from 'querystring'
import pathRegexp from 'path-to-regexp'
import moment from 'moment'
import { routerRedux } from 'dva/router'
import { uploadUrl } from '../config'
import { getToken } from '@/utils/localStorage'

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/
export const isUrl = path => reg.test(path)
export const isAntDesignPro = () => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true
  }

  return window.location.hostname === 'preview.pro.ant.design'
} // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
  const { NODE_ENV } = process.env

  if (NODE_ENV === 'development') {
    return true
  }

  return isAntDesignPro()
}
export const getPageQuery = () => parse(window.location.href.split('?')[1])
/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */

export const getAuthorityFromRouter = (router = [], pathname) => {
  const authority = router.find(
    ({ routes, path = '/' }) =>
      (path && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname))
  )
  if (authority) return authority
  return undefined
}

export const getRouteAuthority = (path, routeData) => {
  let authorities
  routeData.forEach(route => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority
      } // exact match

      if (route.path === path) {
        authorities = route.authority || authorities
      } // get children authority recursively

      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities
      }
    }
  })
  return authorities
}

export function getTimeDistance(type) {
  const now = new Date()
  const oneDay = 1000 * 60 * 60 * 24

  if (type === 'today') {
    now.setHours(0)
    now.setMinutes(0)
    now.setSeconds(0)
    return [moment(now), moment(now.getTime() + (oneDay - 1000))]
  }

  if (type === 'week') {
    let day = now.getDay()

    const beginTime = now.getTime()

    return [moment(beginTime - (6 * oneDay - 1000)), moment(beginTime)]
  }

  if (type === 'month') {
    let day = now.getDay()

    const beginTime = now.getTime()

    return [moment(beginTime - (30 * oneDay - 1000)), moment(beginTime)]
  }

  const year = now.getFullYear()
  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)]
}

export function onTableData(e) {
  if (!!e) {
    const customData =
      e === []
        ? []
        : e.map((item, sign) => {
            const newsItem = { ...item }
            const keys = sign + 1
            newsItem.key = keys
            return newsItem
          })
    return customData
  } else {
    return []
  }
}

// 表格详情解析
export function onTableDataExt(e) {
  if (!!e) {
    const customData =
      e === []
        ? []
        : e.map((item, sign) => {
            const newsItem = { ...item }
            const keys = sign + 1
            newsItem.key = keys
            return newsItem
          })
    return customData
  } else {
    return []
  }
}

export function getParam(name) {
  const search = document.location.href
  const pattern = new RegExp('[?&]' + name + '=([^&]+)', 'g')
  const matcher = pattern.exec(search)
  let items = null
  if (matcher !== null) {
    try {
      items = decodeURIComponent(decodeURIComponent(matcher[1]))
    } catch (e) {
      try {
        items = decodeURIComponent(matcher[1])
      } catch (e) {
        items = matcher[1]
      }
    }
  }
  return items
}

export function goToRouter(dispatch, path) {
  dispatch(routerRedux.push(path))
}

export function downloadFile(href, filename = '') {
  if (href) {
    const download = document.createElement('a')
    download.download = filename
    download.style.display = 'none'
    download.href = href
    document.body.appendChild(download)
    download.click()
    document.body.removeChild(download)
  } else {
    throw Error('下载链接不正确')
  }
}

export const bfUploadFn = param => {
  const serverURL = uploadUrl
  const xhr = new XMLHttpRequest()
  const fd = new FormData()

  const successFn = () => {
    // 假设服务端直接返回文件上传后的地址
    // 上传成功后调用param.success并传入上传后的文件地址
    param.success({
      url: JSON.parse(xhr.responseText).data
    })
  }

  const progressFn = event => {
    // 上传进度发生变化时调用param.progress
    param.progress((event.loaded / event.total) * 100)
  }

  const errorFn = () => {
    // 上传发生错误时调用param.error
    param.error({
      msg: 'unable to upload.'
    })
  }

  xhr.upload.addEventListener('progress', progressFn, false)
  xhr.addEventListener('load', successFn, false)
  xhr.addEventListener('error', errorFn, false)
  xhr.addEventListener('abort', errorFn, false)

  fd.append('file', param.file)
  xhr.open('POST', serverURL, true)
  xhr.setRequestHeader('token', getToken())
  xhr.send(fd)
}
